<template>
  <div class="dialogCom">
    <el-dialog title="编辑角色" :visible.sync="isShow" width="50%">
      <el-form ref="form" label-width="120px" :model="form" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model.trim="form.name" autofocus />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model.trim="form.description" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="footer">
          <el-button @click="isShow = false">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { sysRolePost, sysRolePut } from '@/api/setting'
export default {
  name: 'DialogCom',
  props: {
    tableList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      mode: '',
      isShow: false,
      form: {
        name: '', //	string	必须		角色名称
        description: '' //	string	必须		角色描述
      },
      rules: {
        name: [
          { required: true, message: '必填', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              this.tableList.some(
                (item) =>
                  item.name === value &&
                  (this.mode === 'add' ? true : item.id !== this.form.id)
              )
                ? callback(new Error('角色名重复'))
                : callback()
            },
            trigger: 'change'
          }
        ], //	string	必须		角色名称
        description: [{ required: true, message: '必填', trigger: 'blur' }] //	string	必须		角色描述
      },
      initForm: ''
    }
  },
  watch: {
    isShow: {
      handler(newVal) {
        if (!newVal) {
          this.form = { ...this.initForm }
          this.$refs.form.resetFields()
        }
      }
    }
  },
  created() {
    this.initForm = { ...this.form }
  },
  methods: {
    submit() {
      this.$refs.form.validate(async(result) => {
        if (result) {
          this.mode === 'add'
            ? await sysRolePost(this.form)
            : await sysRolePut(this.form)
          this.isShow = false
          this.$message.success(this.mode === 'add' ? '新增成功' : '编辑成功')
          this.$emit('currentChange', 1)
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.dialogCom {
  .footer {
    text-align: center;
  }
}
</style>
